/**
 * @description Receive data stream to generate blob, create link, download file
 * @param {Function} api API method to export table (required)
 * @param {String} tempName Exported file name (required)
 * @param {Object} params Exported parameters (default {})
 * @param {String} fileType Exported file format (default is .xlsx)
 * */

import { FileLink } from '@/api/modules/entity'

function validateLink(url: string) {
  const pattern = /(ht|f)tp(s?):\/\/[0-9a-zA-Z]?/
  return pattern.test(url)
}

function getFileName(url: string) {
  const pattern = /\/([^/?]+)(\?.*)?$/
  const match = url.match(pattern)
  if (match) {
    return match[1]
  }
  return ''
}

export const usedownloadDoc = async (url: string, fileName = '') => {
  let fileLink = url
  let name = fileName || url
  if (!fileName) {
    name = getFileName(fileLink)
  }
  //判断是不是http
  if (!validateLink(url)) {
    const { data } = await FileLink({ objectKey: url, fileName: name })
    fileLink = data
  }

  console.log(name)
  const eleLink = document.createElement('a')
  eleLink.href = fileLink
  eleLink.download = name //下载后文件名
  eleLink.style.display = 'none'
  // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click() //点击下载
  //下载完成移除元素
  document.body.removeChild(eleLink)
}
